import './index.scss'
import { useMount } from 'ahooks'
import { ConfigProvider } from 'antd'
import { useState, lazy, Suspense } from 'react'

import { GetIndexedDB } from '../Utils/IndexedDB'
import { initWindwoData } from '../Utils/Common'
import { ThemeBackList } from '../Config/themeList'

const Admin = () => {
    const [Theme, setTheme] = useState()

    useMount(async () => {
        initWindwoData(await GetIndexedDB('config'))
        const Theme = await GetIndexedDB('theme')
        setTheme(Theme)
    })

    if (Theme) {
        const { ThemeSet, MenuSet } = Theme
        const { theme, color, backType, backData, blurState, blurColor, blurFilter, modelColor } = ThemeSet
        const { itemColor, itemSelectedColor, itemSelectedBg, iconSize } = MenuSet
        sessionStorage.setItem('theme', color)
        const Home = lazy(() => import(`./Home/${theme}.jsx`))
        const Back = () => {
            const backTypes = {
                image: (src) => <img className='ImageBack' src={src} alt="" />,
                color: (color) => <div className='ColorBack' style={{ '--Back': color }} />,
                patter: (data) => {
                    const [name, ...A] = data.split(',')
                    const style = Object.fromEntries(A.map((value, index) => [`--A0${index + 1}`, value]))
                    return (<div className={`PatterBack ${name}`} style={style} />)
                }
            }
            return (
                <div className='Back'>
                    {blurState && <div className='mask' style={{ '--Color': blurColor, '--Filter': blurFilter }} />}
                    {backTypes[backType]?.(backType === 'image' ? ThemeBackList[backData] : backData)}
                </div>
            )
        }

        return (
            <Suspense>
                <ConfigProvider
                    theme={{
                        token: { colorPrimary: color, colorBgElevated: modelColor },
                        components: {
                            Menu: {
                                itemBg: 'transparent',
                                itemActiveBg: itemSelectedBg,
                                iconSize,
                                itemColor,
                                itemSelectedBg,
                                itemSelectedColor,
                            }
                        }
                    }}
                >
                    <div className='AdminPage'>
                        <Back />
                        <Home />
                    </div>
                </ConfigProvider>
            </Suspense>
        )
    }
}

export default Admin